package com.example.nextgen.util.translate;

import com.aliyun.alimt20181012.Client;
import com.aliyun.alimt20181012.models.TranslateGeneralRequest;
import com.aliyun.alimt20181012.models.TranslateGeneralResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

//@Component
public class Translator {

    @Resource
    AliTranslateConfig aliTranslateConfig;

    /**
     * 使用AK&SK初始化账号Client
     */
    public Client createClient() throws Exception {
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(aliTranslateConfig.getKey())
                // 您的 AccessKey Secret
                .setAccessKeySecret(aliTranslateConfig.getSecret());
        // 访问的域名
        config.setEndpoint(aliTranslateConfig.getEndpoint());
        return new Client(config);
    }

    public String zh2En(String text)  {
        if (!isChinese(text)){
            return text;
        }
        TranslateGeneralRequest translateGeneralRequest = new TranslateGeneralRequest()
                .setFormatType("text")
                .setSourceLanguage("zh")
                .setTargetLanguage("en")
                .setSourceText(text)
                .setScene("general");
        TranslateGeneralResponse response;
        try {
            response = createClient()
                    .translateGeneralWithOptions(translateGeneralRequest, new RuntimeOptions());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return response.getBody().getData().getTranslated();
    }

    private boolean isChinese(String source){
        return Pattern.compile("[\\x{4e00}-\\x{9fa5}]").matcher(source).find();
    }

    private String wordsJoin(String text,String joinString){
        return String.join(joinString, text.split("\\s"));
    }

    private List<String> wordsSplit(String text, String splitString){
        return Arrays.stream(text.split(splitString)).collect(Collectors.toList());
    }

    public List<String> words2En(String text,String joinText){
        String wordsJoin = wordsJoin(text, joinText);
        String en = zh2En(wordsJoin);
        return wordsSplit(en,joinText);
    }
}
